'use strict';

const Controller = require('egg').Controller;

class WishlistController extends Controller {
  // GET /api/wishlist
  async index() {
    const { ctx, service } = this;
    const token = ctx.request.headers.token;
    const tokenData = service.auth.verifyToken(token);

    if (!tokenData) {
      ctx.status = 401;
      ctx.body = { success: false, message: '未登录或token无效' };
      return;
    }

    const ids = await service.wishlist.listByUser(tokenData.userId);
    ctx.body = { success: true, data: ids };
  }

  // POST /api/wishlist { cityId }
  async add() {
    const { ctx, service } = this;
    const token = ctx.request.headers.token;
    const tokenData = service.auth.verifyToken(token);
    if (!tokenData) {
      ctx.status = 401;
      ctx.body = { success: false, message: '未登录或token无效' };
      return;
    }

    const cityId = parseInt(ctx.request.body?.cityId);
    if (!cityId || Number.isNaN(cityId)) {
      ctx.status = 400;
      ctx.body = { success: false, message: 'cityId 参数无效' };
      return;
    }

    const ok = await service.wishlist.add(tokenData.userId, cityId);
    if (!ok) {
      ctx.status = 404;
      ctx.body = { success: false, message: '城市不存在' };
      return;
    }
    ctx.body = { success: true, message: '已加入心愿单' };
  }

  // DELETE /api/wishlist/:cityId
  async remove() {
    const { ctx, service } = this;
    const token = ctx.request.headers.token;
    const tokenData = service.auth.verifyToken(token);
    if (!tokenData) {
      ctx.status = 401;
      ctx.body = { success: false, message: '未登录或token无效' };
      return;
    }

    const cityId = parseInt(ctx.params?.cityId);
    if (!cityId || Number.isNaN(cityId)) {
      ctx.status = 400;
      ctx.body = { success: false, message: 'cityId 参数无效' };
      return;
    }

    const ok = await service.wishlist.remove(tokenData.userId, cityId);
    ctx.body = { success: true, message: ok ? '已从心愿单移除' : '未找到记录' };
  }
}

module.exports = WishlistController;